package com.lykj.modules.shop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lykj.core.excel.util.ExcelUtil;
import com.lykj.core.log.exception.ServiceException;
import com.lykj.core.secure.LykjUser;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.core.tool.utils.DateUtil;
import com.lykj.modules.auth.enums.UserEnum;
import com.lykj.modules.shop.excel.UserExcel;
import com.lykj.modules.shop.excel.UserExtractExcel;
import com.lykj.modules.shop.service.UserBonusService;
import com.lykj.modules.shop.service.UserOrderService;
import com.lykj.modules.shop.vo.UserExtractVO;
import com.lykj.modules.shop.znapi.ZnApiUtils;
import com.lykj.modules.system.entity.User;
import com.lykj.modules.system.service.UserService;
import com.lykj.modules.system.vo.UserVO;
import com.lykj.modules.system.wrapper.UserWrapper;
import io.swagger.annotations.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.lykj.core.mp.support.Condition;
import com.lykj.core.mp.support.Query;
import com.lykj.core.tool.api.R;
import com.lykj.core.tool.utils.Func;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.lykj.core.boot.ctrl.LykjController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 用户表 控制器
 *
 * @author cxl
 * @since 2022-01-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("lykj-shop/user")
@Api(value = "商城会员接口", tags = "商城会员接口")
public class LykjUserController extends LykjController {

	private final UserService userService;
	private final ZnApiUtils znApiUtils;
	private final UserOrderService userOrderService;
	private final UserBonusService userBonusService;

	/**
	 * 商城注册用户
	 */
	@PostMapping("/register")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "商城注册用户", notes = "传入user")
	public R register(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId,
					  @ApiParam(value = "账号", required = true) @RequestParam(required = false) String account,
					  @ApiParam(value = "密码", required = true) @RequestParam(required = false) String password,
					  @ApiParam(value = "验证码", required = true) @RequestParam(required = false) String captcha,
					  @ApiParam(value = "推荐人手机号", required = true) @RequestParam(required = false) String phone,
					  @ApiParam(value = "数据类型", required = false) @RequestParam(required = false) Integer sign) {
		return R.status(userService.register(tenantId, account, password, captcha, phone, sign));
	}
	/**
	 * 商城注册用户
	 */
	@PostMapping("/updateDayWithdrawalLimit")
	@ApiOperation(value = "批量修改日提现额度", notes = "IDS和额度")
	public R updateDayWithdrawalLimit(@RequestBody Map<String, String> params) {
		String ids = params.get("ids");
		String withdrawalLimit = params.get("withdrawalLimit");
		return R.status(userService.updateDayWithdrawalLimit(ids,withdrawalLimit));
	}
	/**
	 * 商城注册用户
	 */
	@PostMapping("/updateBonusStatus")
	@ApiOperation(value = "批量修改红包资格", notes = "IDS和额度")
	public R updateBonusStatus(@RequestBody Map<String, String> params) {
		String ids = params.get("ids");
		String bonusStatus = params.get("bonusStatus");
		return R.status(userService.updateBonusStatus(ids,bonusStatus));
	}



	@PostMapping("/updateSumWithdrawalLimit")
	@ApiOperation(value = "批量修改日提现额度", notes = "IDS和额度")
	public R updateSumWithdrawalLimit(@RequestBody Map<String, String> params) {
		String ids = params.get("ids");
		String withdrawalLimit = params.get("withdrawalLimit");
		return R.status(userService.updateSumWithdrawalLimit(ids,withdrawalLimit));
	}



	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "查看详情（更新实名状态和余额）", notes = "传入id")
	@GetMapping("/info")
	public R<UserVO> info(LykjUser user) {
		User detail = userService.getById(user.getUserId());
		User userTemp = new User();
		userTemp.setId(detail.getId());

		detail.setOrdersTotal(userOrderService.ordersTotal(user.getUserId()));
		detail.setBonusOrders(userOrderService.bonusOrdersTotal(user.getUserId()));
		detail.setBonusTotal(userBonusService.bonusTotal(user.getUserId()));
//		// TODO 个人信息
//		JSONObject customerInfo = znApiUtils.customerInfo(detail.getZnToken(), detail.getZnUserId());
//		if ("200".equals(customerInfo.getString("status"))) {
//			String nickname = customerInfo.getJSONObject("content").getString("nickname");
//			detail.setName(nickname);
//			userService.updateById(detail);
//		}
		// TODO 认证
//		if ("false".equals(detail.getZnAuthenticationed())) {
//			JSONObject returnJson = znApiUtils.authenticationInfo(detail.getZnToken(), detail.getZnUserId());
//			if (returnJson.getJSONObject("content").get("status") != null && "2".equals(returnJson.getJSONObject("content").getString("status"))) {
//				userTemp.setZnAuthenticationed("true");
//				userService.updateById(userTemp);
//			}
//		}
//			// TODO 安全密码
//			if("false".equals(user.getZnAuthenticationed())) {
//				String authenticationed = returnJson.getJSONObject("content").getString("authenticationed");
//				user.setZnAuthenticationed(authenticationed);
//			}
		// TODO 绑卡
//		if (0 == detail.getZnIsBindCard()) {
//			JSONObject returnJson = znApiUtils.bindAccountList(detail.getZnToken(), detail.getZnUserId());
//			try {
//				if (returnJson.getJSONArray("content") != null && returnJson.getJSONArray("content").size() > 0) {
//					userTemp.setZnIsBindCard(1);
//					userService.updateById(userTemp);
//				}
//			} catch (Exception e) {
//				System.out.println("估计登录超时了");
//			}
//		}
		// TODO 签约
//		if ("false".equals(detail.getZnSignContract())) {
//			JSONObject returnJson = znApiUtils.querySignContract(detail.getZnToken(), detail.getZnUserId());
//			if (returnJson.getJSONObject("content") instanceof JSONObject && returnJson.getJSONObject("content").get("responseValue") != null) {
//				String signContract = returnJson.getJSONObject("content").getString("responseValue");
//				userTemp.setZnSignContract(signContract);
//				userService.updateById(userTemp);
//			}
//		}

		// TODO 众鸟余额
//		JSONObject balanceQuery = znApiUtils.balanceQuery(detail.getZnToken(), detail.getZnUserId());
//		if ("200".equals(balanceQuery.getString("status")) && balanceQuery.getJSONObject("content") instanceof JSONObject) {
//			JSONObject balanceQueryContent = balanceQuery.getJSONObject("content");
//			//账户余额
//			if (balanceQueryContent.get("balance") != null) {
//				userTemp.setZnBalance(balanceQueryContent.getString("balance"));
//				userService.updateById(userTemp);
//			}
//		}
		return R.data(UserWrapper.build().entityVO(detail));
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "详情", notes = "传入user")
	public R<UserVO> detail(User user) {
		user.setUserType(UserEnum.APP.getCategory());
		User detail = userService.getOne(Condition.getQueryWrapper(user));
		return R.data(UserWrapper.build().entityVO(detail));
	}


	/**
	 * 分页 用户表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "分页", notes = "传入user")
	public R<IPage<UserVO>> list(UserVO user, Query query) {
//		LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>query().lambda();
//		if (user.getUid() != null) {
//			queryWrapper.eq(User::getUid, user.getUid());
//		}
//		if (Func.isNotBlank(user.getAccount())) {
//			queryWrapper.like(User::getAccount, user.getAccount());
//		}
//		queryWrapper.eq(User::getStatus, 1);//正常状态
//		queryWrapper.eq(User::getUserType, UserEnum.APP.getCategory());
//		if(!AuthUtil.isAdministrator()) {
//			queryWrapper.eq(User::getTenantId, AuthUtil.getTenantId());
//		}
//		IPage<User> pages = userService.page(Condition.getPage(query.setDescs("create_time")), queryWrapper);
//		return R.data(UserWrapper.build().pageVO(pages));
		query.setDescs("id");
		user.setStatus(1);
		user.setUserType(UserEnum.APP.getCategory());
		IPage<UserVO> pages = userService.selectUserPage(Condition.getPage(query), user);
		return R.data(pages);
	}

	/**
	 * 懒加载列表
	 */
	@GetMapping("/lazy-list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "用户账号", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "懒加载列表", notes = "传入user")
	public R<List<UserVO>> lazyList(@ApiIgnore @RequestParam Map<String, Object> user, Long spreadId) {
		List<UserVO> list = userService.lazyList(AuthUtil.getTenantId(), spreadId, user);
		return R.data(list);
	}

	/**
	 * 自定义分页 用户表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "分页", notes = "传入user")
	public R<IPage<UserVO>> page(UserVO user, Query query) {
		user.setUserType(UserEnum.APP.getCategory());
		IPage<UserVO> pages = userService.selectUserPage(Condition.getPage(query), user);
		return R.data(pages);
	}

	/**
	 * 新增 用户表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增", notes = "传入user")
	public R save(@Valid @RequestBody User user) {
		user.setUserType(UserEnum.APP.getCategory());
		return R.status(userService.save(user));
	}

	/**
	 * 修改 用户表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "修改", notes = "传入user")
	public R update(@Valid @RequestBody User user) {
		user.setUserType(UserEnum.APP.getCategory());
		return R.status(userService.updateById(user));
	}

	/**
	 * 新增或修改 用户表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "新增或修改", notes = "传入user")
	public R submit(@Valid @RequestBody User user) {
		user.setUserType(UserEnum.APP.getCategory());
		return R.status(userService.saveOrUpdate(user));
	}

	/**
	 * 删除 用户表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(userService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 平台余额转账
	 */
	@PostMapping("/transferMoney")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "平台余额转账")
	public R<JSONObject> transferMoney(@ApiParam(value = "接收账户", required = true) @RequestParam String account,
									   @ApiParam(value = "转账金额", required = true) @RequestParam BigDecimal number) {
		if (AuthUtil.getUserAccount().equals(account)) {
			throw new ServiceException("接收账户不能是自己!");
		}
		User user1 = userService.getById(AuthUtil.getUserId());
		if (user1.getOpenTransferOutBalance()!=0) {
			throw new ServiceException("账户已经关闭转账!");
		}
		User user = userService.getOne(Wrappers.<User>query().lambda().eq(User::getTenantId, AuthUtil.getTenantId()).eq(User::getAccount, account));
		if (Func.isNull(user)) {
			throw new ServiceException("接收账户不存在，请仔细检查一下!");
		}
		if (user.getOpenTransferInBalance()!=0) {
			throw new ServiceException("接收账户已经关闭转账!");
		}
		return R.status(userService.transferMoney(user.getId(), number));
	}

	/**
	 * 贡献值转余额
	 */
	@PostMapping("/transferContribute")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "贡献值转余额")
	public R<JSONObject> transferContribute(@ApiParam(value = "转换贡献值", required = true) @RequestParam BigDecimal number) {
		return R.status(userService.transferContribute(number));
	}

	/**
	 * 充值余额或积分
	 */
	@PostMapping("/recharge")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "充值余额或积分")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "number", value = "充值数量", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "category", value = "充值类型0余额1积分", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "pm", value = "方向0减少1增加", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "remark", value = "备注", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> recharge(@ApiIgnore @RequestBody Map<String, Object> params) {
		return R.status(userService.recharge(params));
	}

	/**
	 * 领取红包
	 */
	@PostMapping("/bonus")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "领取红包")
	public R<JSONObject> bonus(@ApiParam(value = "红包ID", required = true) @RequestParam Long bonusId) {
		return R.status(userService.bonus(bonusId));
	}

	/**
	 * 提现申请
	 */
	@PostMapping("/withdrawal")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "提现申请")
	public R<JSONObject> withdrawal(@ApiParam(value = "提现金额", required = true) @RequestParam String accountName, @RequestParam String accountNumber, @RequestParam String amount) {
		System.out.println(amount);
		BigDecimal number = new BigDecimal(amount);
		System.out.println(number);
		return R.status(userService.withdrawal(accountName, accountNumber, number));
	}

	/**
	 * 老账号激活
	 */
	@PostMapping("/activate")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "老账号激活", notes = "传入user")
	public R activate(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId,
					  @ApiParam(value = "账号", required = true) @RequestParam(required = false) String account,
					  @ApiParam(value = "密码", required = true) @RequestParam(required = false) String password,
					  @ApiParam(value = "验证码", required = true) @RequestParam(required = false) String captcha
	) {
		return R.status(userService.activate(tenantId, account, password, captcha));
	}

	/**
	 * 积分兑换/余额购买
	 */
	@PostMapping("/redeem")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "积分兑换/余额购买")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "productId", value = "商品ID", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "number", value = "兑换数量", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "contacts", value = "联系人", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "mobile", value = "联系电话", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "shippingAddress", value = "联系地址", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "payType", value = "支付类型", paramType = "query", required = false, dataType = "String")
	})
	public R redeem(@ApiIgnore @RequestBody Map<String, Object> params
	) {
		return R.status(userOrderService.redeem(params));
	}

	/**
	 * 积分兑换/余额购买
	 */
	@PostMapping("/wxredeem")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "积分兑换/余额购买")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "productId", value = "商品ID", paramType = "query", required = true, dataType = "String"),
			@ApiImplicitParam(name = "number", value = "兑换数量", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = "contacts", value = "联系人", paramType = "query", required = true, dataType = "String"),
			@ApiImplicitParam(name = "mobile", value = "联系电话", paramType = "query", required = true, dataType = "String"),
			@ApiImplicitParam(name = "shippingAddress", value = "联系地址", paramType = "query", required = true, dataType = "String")
	})
	public R wxredeem(@ApiIgnore @RequestBody Map<String, Object> params
	) {
		return R.data(userOrderService.wxredeem(params));
	}

	/**
	 * 导出会员数据
	 */
	@GetMapping("export")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "会员数据", notes = "传入user")
	public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) {
		UserVO user = JSON.parseObject(JSON.toJSONString(params), UserVO.class);
		List<UserExcel> listExcel = userService.export(user);
		ExcelUtil.export(response, "会员数据" + DateUtil.time(), "会员数据", listExcel, UserExcel.class);
	}
}
